package org.example.maven.museumuser.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
    // 修改 SIGN_KEY 为至少 32 字节（32 字符）
    private static final String SECRET_KEY = "aVeryLongAndSecureSecretKeyWithAtLeast32BytesLength123";
    private static final Key KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
    private static final Long EXPIRE = 3600000L;		//过期时间

    public static String getUserJwt(Map<String,Object> claims){
        String jwt= Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(KEY, SignatureAlgorithm.HS256)
                .compact();
        return jwt;
    }
    public static Map<String,Object> Parse(String token){
        return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
    //获取用户名字
    public static String getJwtUsername(String token){
        Map<String, Object> claims = JwtUtils.Parse(token);
        Object usernameValue = ((Map<?, ?>) claims).get("phone");
        return (String) usernameValue;
    }
    //获取用户id
    public static Integer getJwtUserId(String token){
        Map<String, Object> claims = JwtUtils.Parse(token);
        Object usernameValue = ((Map<?, ?>) claims).get("id");
        return (Integer) usernameValue;
    }
    /**
     * 验证 JWT 是否合法
     */
    public static boolean validateJwt(String token) {
        try {
            Parse(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
